const std = @import("std");
const jetzig = @import("jetzig");
const article_service = @import("../../../service/article_service.zig");
const const_val = @import("../../../utils/const_value.zig");
const myjwt = @import("../../../utils/myjwt.zig");

// 限定index方法只能响应json
pub const formats: jetzig.Route.Formats = .{
    .index = &.{.json},
};

/// 获取文章列表（文章管理页，响应json）
pub fn index(req: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    const query = try req.httpz_request.query();
    const page_size_str = query.get("page_size") orelse return req.render(.bad_request);
    const page_num_str = query.get("page_num") orelse return req.render(.bad_request);
    const page_size = try std.fmt.parseInt(u32, page_size_str, 10);
    const page_num = try std.fmt.parseInt(u32, page_num_str, 10);
    // std.debug.print("page_size: {d}, page_num: {d} \n", .{ page_size, page_num });

    // 下面这种方式获取参数很麻烦，所以还是用上面的方式吧
    // const qp = req.queryParams() catch return req.render(.bad_request);
    // const page_size: i128 = qp.*.getT(.integer, "page_size") orelse 10;
    // const page_num: i128 = qp.*.getT(.integer, "page_num") orelse 1;
    // std.debug.print("page_size: {d}, page_num: {d} \n", .{ page_size, page_num });

    const token = req.getHeader("authorization") orelse "";
    // std.debug.print("token: {s}\n", .{token});
    // token为空时，返回401
    if (token.len == 0) {
        var root = try data.object();
        try root.put("code", 401);
        try root.put("msg", "token有误");
        try root.put("data", null);
        return req.fail(.unauthorized);
    }

    // 验证token
    const exp = myjwt.ExpectedPayload{ .iss = const_val.JWT_ISS, .sub = const_val.JWT_SUB };
    const is_ok = myjwt.verifyToken(exp, token) catch false;
    if (!is_ok) {
        var root = try data.object();
        try root.put("code", 401);
        try root.put("msg", "token验证失败");
        try root.put("data", null);
        return req.fail(.unauthorized);
    }

    // 获取文章列表
    const articles = article_service.getArticleListPaginate(page_size, page_num) catch {
        var root = try data.object();
        try root.put("code", 500);
        try root.put("msg", "服务器内部错误");
        try root.put("data", null);
        return req.fail(.internal_server_error);
    };
    // 获取文章总数
    const total = article_service.getArticleTotalCount() catch {
        var root = try data.object();
        try root.put("code", 500);
        try root.put("msg", "服务器内部错误");
        try root.put("data", null);
        return req.fail(.internal_server_error);
    };

    var root = try data.object();
    try root.put("code", 200);
    try root.put("msg", "ok");
    try root.put("total", total);

    var arts_array = try data.array();
    for (articles) |art| {
        var art_obj = try data.object();
        try art_obj.put("id", art.id);
        try art_obj.put("title", art.title);
        try art_obj.put("cate_name", art.cate_name);
        try art_obj.put("istop", art.istop);
        try art_obj.put("description", art.description);
        try art_obj.put("content", art.content);
        try art_obj.put("created_at", art.created_at);
        try art_obj.put("updated_at", art.updated_at);

        try arts_array.append(art_obj);
    }
    try root.put("data", arts_array);

    return req.render(.ok);
}
